const logger = require('../utils/logger');

/**
 * 请求日志中间件
 * 记录请求的详细信息，包括请求方法、URL、IP地址、请求体等
 * 
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @param {Function} next - 下一个中间件函数
 */
function requestLogger(req, res, next) {
  // 获取请求信息
  const method = req.method;
  const url = req.originalUrl || req.url;
  const ip = req.ip || req.connection.remoteAddress;
  const userAgent = req.headers['user-agent'] || 'Unknown';
  
  // 记录基本请求信息
  logger.info(`${method} ${url} - IP: ${ip} - User-Agent: ${userAgent}`);
  
  // 记录请求体（如果存在且不是文件上传）
  if (['POST', 'PUT', 'PATCH'].includes(method) && 
      req.body && 
      !req.is('multipart/form-data') && 
      Object.keys(req.body).length > 0) {
    
    // 创建请求体的安全副本（排除敏感字段）
    const safeBody = { ...req.body };
    
    // 移除敏感字段
    const sensitiveFields = ['password', 'token', 'secret', 'apiKey', 'api_key'];
    sensitiveFields.forEach(field => {
      if (safeBody[field]) {
        safeBody[field] = '******';
      }
    });
    
    // 记录请求体（限制大小）
    const bodyString = JSON.stringify(safeBody);
    const truncatedBody = bodyString.length > 1000 
      ? bodyString.substring(0, 1000) + '... [截断]' 
      : bodyString;
    
    logger.debug(`请求体: ${truncatedBody}`);
  }
  
  // 记录响应时间和状态码
  const startTime = Date.now();
  
  // 在响应结束时记录响应信息
  res.on('finish', () => {
    const duration = Date.now() - startTime;
    const statusCode = res.statusCode;
    
    // 根据状态码选择日志级别
    if (statusCode >= 500) {
      logger.error(`${method} ${url} - ${statusCode} - ${duration}ms`);
    } else if (statusCode >= 400) {
      logger.warn(`${method} ${url} - ${statusCode} - ${duration}ms`);
    } else {
      logger.info(`${method} ${url} - ${statusCode} - ${duration}ms`);
    }
  });
  
  next();
}

module.exports = requestLogger;